package utils

import (
	"encoding/json"
	"io"
	"os"
	"path/filepath"

	"gopkg.in/yaml.v3"
)

func FormatJSONString(v any) string {
	jsonBytes, _ := json.Marshal(v)
	return string(jsonBytes)
}

func MustRead(path string) string {
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	bytes, err := io.ReadAll(file)
	if err != nil {
		panic(err)
	}
	return string(bytes)
}

func MustLoad[T any](path string) T {
	var result T
	ext := filepath.Ext(path)
	switch ext {
	case ".json":
		result = mustLoadJSON[T](path)
	case ".yaml", ".yml":
		result = mustLoadYAML[T](path)
	default:
		panic("unsupported file extension")
	}
	return result
}

func mustLoadJSON[T any](path string) T {
	var result T
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	decoder := json.NewDecoder(file)
	err = decoder.Decode(&result)
	if err != nil {
		panic(err)
	}
	return result
}

func mustLoadYAML[T any](path string) T {
	var result T
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	decoder := yaml.NewDecoder(file)
	err = decoder.Decode(&result)
	if err != nil {
		panic(err)
	}
	return result
}
